package com.peanut.baby.mvp.qadetail;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;

import androidx.annotation.NonNull;

import com.peanut.baby.InitManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseResponse;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.QA;
import com.peanut.baby.model.QAComment;
import com.peanut.baby.model.QaRel;
import com.peanut.baby.model.ShareType;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.model.VarPoint;
import com.peanut.baby.uploader.UploadMgr;
import com.tencent.mars.xlog.Log;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

import cn.nekocode.rxlifecycle.RxLifecycle;
import io.reactivex.Observable;

/**
 * Created by anonymouslystudio on 2017/7/27.
 */

public class QADetailPresenter implements QADetailContract.Presenter{
    private static final String TAG = QADetailPresenter.class.getSimpleName();
    private QADetailContract.View view;
    private Activity activity;
    public QADetailPresenter(QADetailContract.View view,Activity activity){
        this.view = view;
        this.activity = activity;

    }

    @Override
    public void checkAudioPermission(final Activity act) {
        AndPermission.with(act)
                .requestCode(100)
                .permission(Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .rationale(new RationaleListener(){

                    @Override
                    public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
                        AlertDialog.newBuilder(act)
                                .setTitle("提醒")
                                .setMessage("录音功能需要您授予对应的权限")
                                .setPositiveButton("授予", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.resume();
                                    }
                                })
                                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.cancel();
                                    }
                                })
                                .show();
                    }
                })
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        Log.d("LauncherActivity","PermissionListener.SUCCESS");
                        view.onAudioPermissionGranted();
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        Log.d("LauncherActivity","PermissionListener.FAIL");
                        view.onAudioPermissionDenied();
                    }
                })
                .start();
    }

    @Override
    public void getQAAnswerVoice(String id) {
        Observable obs = RetrofitClient.getInstance().getQaAnswerAudio(id, InitManager.getInstance().getUserId(),InitManager.getInstance().getUser().userToken);
        obs.compose(BaseScheduler.<BaseResponse<String>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<String>() {
            @Override
            protected void onHandleSuccess(String o) {
                view.onAnswerVoiceGet(o);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onRequestFailed(code,"请求音频失败 "+msg);
            }

        });
    }

    @Override
    public void praiseQA(String questionId) {
        Observable obs = RetrofitClient.getInstance().praiseQA(questionId, InitManager.getInstance().getUserId(),InitManager.getInstance().getUser().userToken);
        obs.compose(BaseScheduler.<BaseResponse<QA>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<QA>() {
            @Override
            protected void onHandleSuccess(QA o) {
                view.onPraiseSuccess(o);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onRequestFailed(code,"请求失败 "+msg);
            }

        });
    }

    @Override
    public void sharePoint(String questionId) {
        Observable obs = RetrofitClient.getInstance().sharePoint(InitManager.getInstance().getUserId(),
                ShareType.TYPE_SHARE_QA+"",questionId);
        obs.compose(BaseScheduler.<VarPoint>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<VarPoint>() {
            @Override
            protected void onHandleSuccess(VarPoint o) {
                InitManager.getInstance().getUser().userPoint = o.totalPoint;
                InitManager.getInstance().updateLocalUser();
                view.onSharePointSuccess("花生米加"+o.variedPoint+",总花生米"+o.totalPoint);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                Log.w(TAG,"sharePoint failed "+msg);
//                view.onSharePointSuccess(msg);
            }
        });
    }

    @Override
    public void getQARel(int id) {
        Observable obs = RetrofitClient.getInstance().getQaRel(id, InitManager.getInstance().getUserId());
        obs.compose(BaseScheduler.<BaseResponse<QAComment>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<QaRel>() {
                    @Override
                    protected void onHandleSuccess(QaRel o) {
                        view.onQARelGet(true,o,"");
                    }

                    @Override
                    protected void onHandleError(String code,String msg) {
                        view.onQARelGet(false,null,"msg");
                    }

                });
    }

    @Override
    public void sendComment(String text,String questionid) {
        Observable obs = RetrofitClient.getInstance().commentQA(questionid, InitManager.getInstance().getUserId(),QAComment.CONTENT_TYPE_TEXT+"",InitManager.getInstance().getUser().userToken,text);
        obs.compose(BaseScheduler.<BaseResponse<QAComment>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<QAComment>() {
            @Override
            protected void onHandleSuccess(QAComment o) {
                view.onSendCommentFinished(true,"",o);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                Log.d(TAG,"sendComment failed "+msg);
                view.onRequestFailed(code,"评论失败 "+msg);
            }

        });
    }

    @Override
    public void sendAnswer(String voiceUrl, long duration, String questionId) {
        Observable obs = RetrofitClient.getInstance().answerQuestion(questionId,
                InitManager.getInstance().getUserId(),
                voiceUrl,
                duration,
                InitManager.getInstance().getUser().userToken,InitManager.getInstance().getUserId());
        obs.compose(BaseScheduler.<BaseResponse<QA>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<QA>() {
            @Override
            protected void onHandleSuccess(QA o) {
                view.onSendAnswerFinished(true,"",o);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onRequestFailed(code,"回答失败 "+msg);
            }

        });
    }

    @Override
    public void getCommentList(String id,int pageNo, int pageSize) {
        Observable obs = RetrofitClient.getInstance().getQaCommentList(id,pageNo,pageSize);
        obs.compose(BaseScheduler.<BaseResponse<List<QAComment>>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<List<QAComment>>() {
            @Override
            protected void onHandleSuccess(List<QAComment> o) {
                view.onGetCommentFinished(true,"",o);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onGetCommentFinished(false,msg,null);
            }

        });
    }

    @Override
    public void getQADetail(String id) {
        Observable obs = RetrofitClient.getInstance().getQaDetail(id, InitManager.getInstance().getUserId());
        obs.compose(BaseScheduler.<BaseResponse<QA>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<QA>() {
            @Override
            protected void onHandleSuccess(QA o) {
                view.onGetQADetailFinished(true,"",o);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onGetQADetailFinished(false,msg,null);
            }

        });
    }

    @Override
    public void uploadCommentVoice(final String path, final int duration) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                UploadMgr.getInstance().uploadImage(path,
                        UploadMgr.UPLOAD_TYPE_QA, InitManager.getInstance().getUserId(), new UploadMgr.UploadListener() {
                            @Override
                            public void onQueryToken() {
                            }

                            @Override
                            public void onStartUpload() {

                            }

                            @Override
                            public void onUploadProgress(int total) {

                            }

                            @Override
                            public void onUploadSuccess(UploadConf config) {
                                config.duration = duration;
                                view.onAudioUploadFinished(true,"",config);
                            }

                            @Override
                            public void onUploadFailed(UploadConf config,String failed) {
                                view.onAudioUploadFinished(false,failed,config);
                            }
                        });
            }
        }).start();
    }
}
